package com.qinggeng.project.system.service.impl;

import com.qinggeng.common.constant.UserConstants;
import com.qinggeng.common.enums.UserTypeEnum;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.utils.DateUtils;
import com.qinggeng.common.utils.IdCodeUtils;
import com.qinggeng.common.utils.SecurityUtils;
import com.qinggeng.common.utils.StringUtils;
import com.qinggeng.project.api.dto.ShopDto;
import com.qinggeng.project.api.dto.ShopStatisDto;
import com.qinggeng.project.system.domain.Shop;
import com.qinggeng.project.system.domain.SysUser;
import com.qinggeng.project.system.domain.SysUserRole;
import com.qinggeng.project.system.mapper.ShopMapper;
import com.qinggeng.project.system.mapper.SysUserMapper;
import com.qinggeng.project.system.mapper.SysUserRoleMapper;
import com.qinggeng.project.system.service.IShopService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商户信息Service业务层处理
 *
 * @author qinggeng
 * @date 2020-05-29
 */
@Service
public class ShopServiceImpl implements IShopService {
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 查询商户信息
     *
     * @param id 商户信息ID
     * @return 商户信息
     */
    @Override
    public Shop selectShopById(Long id) {
        return shopMapper.selectShopById(id);
    }

    /**
     * 查询商户信息列表
     *
     * @param shop 商户信息
     * @return 商户信息
     */
    @Override
    public List<Shop> selectShopList(Shop shop) {
        List<Shop> list=shopMapper.selectShopList(shop);

        return list;
    }

    /**
     * 新增商户信息
     *
     * @param shop 商户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertShop(Shop shop) {
        shop.setCreateTime(DateUtils.getNowDate());
        //标记为存在
        shop.setDelFalg("10");
        shop.setBalance(new BigDecimal(0));
        shop.setOpenState(0);//默认开启 非0为否
        Long userId = this.addSystemUser(shop);
        shop.setUserId(userId);
        shop.setInviteCode(IdCodeUtils.toSerialCode(userId));
        return shopMapper.insertShop(shop);
    }

    //添加系统用户信息
    public Long addSystemUser(Shop shop) {
        SysUser sysUser = new SysUser();
        //判别用户账号是否存在
        if (UserConstants.NOT_UNIQUE.equals(sysUserMapper.checkUserNameUnique(shop.getUserName(), new String[]{UserTypeEnum.SHOP.getCode()}))) {
            throw new CustomException("新增用户'" + shop.getUserName() + "'失败，登录账号已存在", 500);
        } else if (UserConstants.NOT_UNIQUE.equals(sysUserMapper.checkPhoneUnique(shop.getContactPhone(), new String[]{UserTypeEnum.SHOP.getCode()}))) {
            throw new CustomException("新增用户'" + shop.getUserName() + "'失败，手机号码已存在");
        }
        sysUser.setUserName(shop.getUserName());
        sysUser.setNickName(shop.getName());
        sysUser.setUserType(UserTypeEnum.SHOP.getCode()); //系统用户
        sysUser.setPhonenumber(shop.getContactPhone());
        sysUser.setSex("2"); //未知
        if (shop.getStoreImgs() != null) {
            sysUser.setAvatar(shop.getStoreImgs().split(",")[0]);
        }
        sysUser.setCreateBy(SecurityUtils.getUsername());
        sysUser.setRealPwd(shop.getPassword());
        sysUser.setPassword(SecurityUtils.encryptPassword(shop.getPassword()));
        sysUser.setCreateTime(new Date());
        //此处默认为商户管理员
        sysUser.setRoleIds(new Long[]{3l});
        int i = sysUserMapper.insertUser(sysUser);
        if (i < 0) {
            throw new CustomException("初始化用户信息失败！");
        } else {
            this.insertUserRole(sysUser);
        }
        return sysUser.getUserId();
    }

    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                sysUserRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 修改商户信息
     *
     * @param shop 商户信息
     * @return 结果
     */
    @Override
    public int updateShop(Shop shop) {
        shop.setUpdateTime(DateUtils.getNowDate());
//        SysUser sysUser = sysUserMapper.selectUserById(shop.getUserId());
//        if (sysUser != null) {
//            if (!sysUser.getPassword().equals(SecurityUtils.encryptPassword(shop.getPassword()))) {
//                sysUser.setRealPwd(shop.getPassword());
//                sysUser.setPassword(SecurityUtils.encryptPassword(shop.getPassword()));
//                sysUserMapper.updateUser(sysUser);
//            }
//        }
        return shopMapper.updateShop(shop);
    }

    /**
     * 批量删除商户信息
     *
     * @param ids 需要删除的商户信息ID
     * @return 结果
     */
    @Override
    public int deleteShopByIds(Long[] ids) {
        return shopMapper.deleteShopByIds(ids);
    }

    /**
     * 删除商户信息信息
     *
     * @param id 商户信息ID
     * @return 结果
     */
    @Override
    public int deleteShopById(Long id) {
        return shopMapper.deleteShopById(id);
    }

    @Override
    public Shop selectShopDetilByUserId(Long userId) {
        return shopMapper.selectShopDetilByUserId(userId);
    }

    @Override
    public boolean updateShopLog(Long userId, String path) {
        return shopMapper.updateShopLog(userId, path);
    }

    @Override
    public Shop selectShopByLocation(Float lng, Float lat) {
        return shopMapper.selectShopByLocation(lng, lat);
    }

    @Override
    public Shop selectShopByInviteCode(String inviteCode) {
        return shopMapper.selectShopByInviteCode(inviteCode);
    }

    @Override
    public List<ShopDto> selectShopDtoList(Shop where) {
        return shopMapper.selectShopDtoList(where);
    }

    @Override
    public ShopStatisDto getShopInfoById(Long id) {
        return shopMapper.getShopInfoById(id);
    }

    /**
     * 根据店铺Id集合查询所有的商户对象
     * @param shopIdList
     * @return
     */
    @Override
    public List<Shop> selectShopByIds(List<Long> shopIdList) {
        return shopMapper.selectShopByIds(shopIdList);
    }
}
